
-- 跨服工会战 数据
local CSGuildWarData = class("CSGuildWarData")
local CSGuildWarMatchInfo = import(".CSGuildWarMatchInfo")
local CSGuildWarMemberInfo = import(".CSGuildWarMemberInfo")
local CSGuildWarGuildInfo = import(".CSGuildWarGuildInfo")
local CSGuildWarReportInfo = import(".CSGuildWarReportInfo")
local CSGuildWarSeasonInfo = import(".CSGuildWarSeasonInfo")
local Task = import(".Task")

local CrossServerGuildWarHelper = require("app.crossServer.views.guildWar.CrossServerGuildWarHelper")

function CSGuildWarData:ctor()
    self._curMatchInfo = nil
    self._isTodayEnd = false
    self._ticketState = nil
    self._status = 0
    -- 缓存 我在本公会的排名
    self._myInGuildPowerRank = nil
    self._myGuildMemberNum = nil
    self._lastReqInGuildPowerRankTime = nil -- 上一次请求 本公会排名数据
    -- 缓存 上一届 冠军
    self._lastSeasonRankData = nil --
    self._lastSeasonRankDataExpireTime = nil -- 过期时间
    self._curSeason = 0
    --
    self._curHp = 0
    self._score = 0 -- 本场的战功
end



function CSGuildWarData:getScore()
    return self._score
end

--  0关闭 1开启 2 提示状态
function CSGuildWarData:getOpenStatus()
    return self._status
end

function CSGuildWarData:isOpen()
    self:_updateOpenStatus(true) --检查 是否已经结束
    return self._status == 1
end


function CSGuildWarData:setHp(hp)
    if self._curHp ~= hp then
        
        EM:notify(ViewEvent.CSGuildWar_HPChange)
    end
    self._curHp = hp
 
end

function CSGuildWarData:getHp()
    return self._curHp or 0
end

function CSGuildWarData:setOpenStatus(status)
    self._status = status
    if self._status == 2 then
        local params = {
            remindId = Constant.FUNC_TYPE_CS_GUILD_WAR,
        }
        local desktopController = UIHandler:getDesktopController()
        if desktopController then
            desktopController:insertFourthTips( params )
        end
    end

    EM:notify(ViewEvent.CSGuildWar_DesktopTrackView)
end

function CSGuildWarData:_updateOpenStatus(isNeedDispatch)
    if self._status == 1 then
        if self:isFightEnd() == true then
            self._status = 0
            if isNeedDispatch then
                EM:notify(ViewEvent.CSGuildWar_DesktopTrackView)
            end
            return
        end
        local curTime = math.floor(app.session:getServerTime()) or os.time()
        local maxEndTime = CrossServerGuildWarHelper.getGuildWarMaxEndTimeStamp()
        if curTime > maxEndTime then
            self._status = 0
            if isNeedDispatch then
                EM:notify(ViewEvent.CSGuildWar_DesktopTrackView)
            end
            return
        end
    end
end

-- 当前 是否是 跨服工会战准备地图
function CSGuildWarData:isCSGuildWarPrepareMap()
    return CrossServerGuildWarHelper.isCSGuildWarPrepareMap()
end

-- 我当前的公会是否可以参与
function CSGuildWarData:isMyGuildCanJoin()
    return self._curMatchInfo ~= nil
end

function CSGuildWarData:isMyGuildWin()
    if self._curMatchInfo then
        return self._curMatchInfo:isLeftWin()
    end
end

-- 获取我是否可以参与的状态 名额 CSGuildWarTicketState
function CSGuildWarData:getTicketState()
    if self._ticketState == 1 then
        return Enums.CSGuildWarTicketState.Yes
    elseif self._ticketState == 2 then
        return Enums.CSGuildWarTicketState.No
    else
        return Enums.CSGuildWarTicketState.Unknow 
    end
end

--获取对战信息
function CSGuildWarData:getCurMatchInfo()
    return self._curMatchInfo
end

function CSGuildWarData:getTasks()
    return self._tasks or CrossServerGuildWarHelper.getTasks()
end

-- 判断 工会战是否已结束
function CSGuildWarData:isFightEnd()
    if self._curMatchInfo then
        return self._curMatchInfo:getWinner() ~= nil
    end
end

-- 获取 我在本公会战力的排名 -- 缓存起来 
-- forceUpdate 强制刷新
function CSGuildWarData:reqMyInGuildPowerRank(forceUpdate)
    local isReq = false
    if not self._myInGuildPowerRank or forceUpdate then
        isReq = true
    end
    --
    if not isReq then
        local curTime = math.floor(app.session:getServerTime() or os.time())
        -- 缓存 5分钟
        if self._lastReqInGuildPowerRankTime and curTime - self._lastReqInGuildPowerRankTime > 300 then
            isReq = true
        end
    end

    if isReq then
        -- 刷新 我在当前公会的排名
        self:C2S_GuildMemberList()
    else
        scheduler.newCron(function()
            EM:notify(ViewEvent.CSGuildWar_MyPowerRankInGuild, self._myInGuildPowerRank, self._myGuildMemberNum)
        end, 0.01)
    end
    return self._myInGuildPowerRank
end

function CSGuildWarData:getMyGuildMemberNum()
    return self._myGuildMemberNum
end

function CSGuildWarData:getMyInGuildPowerRank()
    return self._myInGuildPowerRank
end

-- 缓存 上一届 赛季信息 
function CSGuildWarData:reqLastSeaonRankData()
    local isReq = false
    if not self._lastSeasonRankData then
        isReq = true
    end
    local curTime = math.floor(app.session:getServerTime() or os.time())
    if not isReq and self._lastSeasonRankDataExpireTime and curTime > self._lastSeasonRankDataExpireTime then
        isReq = true
    end
    if isReq then
        self:C2S_WorldGuildWarSeasonInfo()
    else
        scheduler.newCron(function()
            EM:notify(ViewEvent.CSGuildWar_SeasonRank, self._lastSeasonRankData, self._curSeason)
        end, 0.01)
    end
end

-- 获取 今日的比赛状态
function CSGuildWarData:getTodayStage()
    local curTime = math.floor(app.session:getServerTime() or os.time())
    local startH, startM, startS = CrossServerGuildWarHelper.getGuildWarGetTicketTime()
    local resetH, resetM, resetS = CrossServerGuildWarHelper.getGuildWarResetTime()
    local ticketTime = app:getServerTimeByHMSW(startH, startM, startS, nil, false) -- 准备开始时间
    local resetTime = app:getServerTimeByHMSW(resetH, resetM, resetS, nil, true) --下次重置时间
    -- 当前时间 < 今日开始时间
    if curTime < ticketTime then
        -- 重置时间 < 开始时间  说明 上次结果还没重置 
        if resetTime < ticketTime then
            return Enums.CSGuildWarTodayStage.End
        else
            return Enums.CSGuildWarTodayStage.NotBegin
        end
    else
        local startPrepareTime = tonumber(GD:getCSGuildWarPar("StartPrepareTime", "240"))
        self._battlePrepareTime = tonumber(GD:getCSGuildWarPar("BattlePrepareTime", "60"))
        local startTime = ticketTime + startPrepareTime + self._battlePrepareTime -- 开始时间 + 第一次战斗的准备时间
        if curTime < startTime then
            -- 获取参赛资格阶段
            if Enums.CSGuildWarTicketState.Unknow == self:getTicketState() then
                return  Enums.CSGuildWarTodayStage.GetTicketStart
            else
                return  Enums.CSGuildWarTodayStage.GetTicketEnd
            end
        else
            --什么时候结束 不固定 服务器决定
            if self:isFightEnd() then
                return Enums.CSGuildWarTodayStage.End
            else
                return Enums.CSGuildWarTodayStage.Fighting
            end
        end
    end
end

-- function CSGuildWarData:_setTicketState(status)
--     if self._ticketState ~= status then
--         self._ticketState = status
--         EM:notify(ViewEvent.CSGuildWar_TicketStateChange)
--     end
-- end
--跨服公会战对阵信息
function CSGuildWarData:C2S_WorldGuildWarInfo()
    app.session:request("pb_world.C2S_WorldGuildWarInfo",{},function(msg)
        local match = rawget(msg, "match")
        -- match = self:testMatchInfo()
        -- dump(msg, "C2S_WorldGuildWarInfo=====>>> ", 5)
        if match then
            self._curMatchInfo = CSGuildWarMatchInfo.new()
            self._curMatchInfo:read(match)
        else
            self._curMatchInfo = nil
        end
        local status = rawget(msg, "status")
        self._ticketState = status
        self:_updateOpenStatus(true)
        EM:notify(ViewEvent.CSGuildWar_MatchInfo)
	end)
end

--跨服公会战赛程
function CSGuildWarData:C2S_WorldGuildWarMatch()
    app.session:request("pb_world.C2S_WorldGuildWarMatch",{},function(msg)
        local matches = rawget(msg, "matches") or {}
        -- dump(matches, "C2S_WorldGuildWarMatch=====>>> ", 5)
        local datas = {}
        for k, v in pairs(matches) do
            -- 确保 必须有一个公会
            local guild1 = rawget(v, "guild1")
            if guild1 then
                local m = CSGuildWarMatchInfo.new()
                m:read(v)
                table.insert( datas, m )
            else
                print("==========>>> guild1 data is nil")
            end
        end
        

        EM:notify(ViewEvent.CSGuildWar_ScheduleInfo, datas)
	end)
end

--跨服公会战排行 战绩榜
function CSGuildWarData:C2S_WorldGuildWarRank(cb)
    app.session:request("pb_world.C2S_WorldGuildWarRank",{},function(msg)
        local guilds = rawget(msg, "guilds") or {}
        -- dump(guilds, "C2S_WorldGuildWarRank=====>>> ", 5)
        local datas = {}
        for k, v in pairs(guilds) do
            local m = CSGuildWarGuildInfo.new()
            m:read(v)
            table.insert( datas, m )
        end
        table.sort( datas, function(a, b)
            return a:getRank() < b:getRank()
        end )

        if cb then
            cb(datas)
        end

        EM:notify(ViewEvent.CSGuildWar_GuildRankInfo, datas)
	end)
end

--跨服公会战排行 战绩榜
function CSGuildWarData:C2S_WorldGuildWarMemberRank()
    app.session:request("pb_world.C2S_WorldGuildWarMemberRank",{},function(msg)
        local members = rawget(msg, "members") or {}
        -- dump(members, "C2S_WorldGuildWarMemberRank=====>>> ", 5)
        local datas = {}
        for k, v in pairs(members) do
            local m = CSGuildWarMemberInfo.new()
            m:read(v)
            table.insert( datas, m )
        end
        EM:notify(ViewEvent.CSGuildWar_MemberInfo, datas)
	end)
end

-- 
function CSGuildWarData:C2S_EnterWorldGuildWarMap()
    -- 跨服匹配中，不能进入跨服公会战
    if app:sendMsg("TeamModel", "isInCrossMatch") then
        display.pushToast(L("CrossServerTips5"))
        return
    end
    -- 跨服副本中，不能进入跨服公会战
    if DungeonManager:isCrossDungeon() then
        display.pushToast(L("CrossServerTips26"))
        return
    end

    app.session:request("pb_world.C2S_EnterWorldGuildWarMap",{},function(msg)
	end)
end

function CSGuildWarData:C2S_LeaveWorldGuildWarMap()
    app.session:request("pb_world.C2S_LeaveWorldGuildWarMap",{},function(msg)

	end)
end

function CSGuildWarData:C2S_WorldGuildWarBattleField()
    app.session:request("pb_world.C2S_WorldGuildWarBattleField",{},function(msg)
        local match = rawget(msg, "match")
        -- match = self:testMatchInfo()
        -- dump(match, "C2S_WorldGuildWarBattleField=====>>> ", 5)
        if match then
            self._curMatchInfo = CSGuildWarMatchInfo.new()
            self._curMatchInfo:read(match)
        else
            self._curMatchInfo = nil
        end

        self._score = rawget(msg, "score") or 0
        self:_updateOpenStatus(true)
        EM:notify(ViewEvent.CSGuildWar_MatchInfo)
	end)
end

--
function CSGuildWarData:C2S_WorldGuildWarReport(matchId, cb)
    app.session:request("pb_world.C2S_WorldGuildWarReport",{matchId = matchId},function(msg)
        -- dump(msg, "C2S_WorldGuildWarReport=====>>> ", 5)
        local reportInfo = CSGuildWarReportInfo.new()
        reportInfo:read(msg)
        if cb then
            cb(reportInfo)
        end
        EM:notify(ViewEvent.CSGuildWar_FightReport, reportInfo)
	end)
end

function CSGuildWarData:C2S_WorldGuildWarSeasonInfo(season)
    if not season then
        season = 0
    end
    app.session:request("pb_world.C2S_WorldGuildWarSeasonInfo",{season = season},function(msg)
        -- dump(msg, "C2S_WorldGuildWarSeasonInfo=====>>> ", 5)
        local datas = {}
        local seasonInfo = rawget(msg, "info")
        if seasonInfo then
            datas.season = rawget(seasonInfo, "season") or 0
            datas.guilds = {}
            for k, v in pairs(rawget(seasonInfo, "guilds") or {}) do
                local seasonInfo = CSGuildWarSeasonInfo.new()
                seasonInfo:read(v)
                table.insert(datas.guilds, seasonInfo)
            end
            table.sort( datas.guilds, function(a,b)
                return a:getRank() < b:getRank()
            end )
        else
            datas.guilds = {}
            datas.season = 0
        end

        self._lastSeasonRankData = datas
        local resetH, resetM, resetS = CrossServerGuildWarHelper.getGuildWarResetTime()
        self._lastSeasonRankDataExpireTime = app:getServerTimeByHMSW(resetH, resetM, resetS, nil, true) --下次重置时间
        self._curSeason = rawget(msg, "seasonNow") or 0
        EM:notify(ViewEvent.CSGuildWar_SeasonRank, datas, self._curSeason)
	end)
end


-- 获取 在公会 战力排行
function CSGuildWarData:C2S_GuildMemberList()
    local guildId = UD:getGuildId()
    if not guildId or guildId == 0 then
        return
    end

    app.session:request("pb_guild.C2S_GuildMemberList",{gid = guildId},function(msg)
        self._lastReqInGuildPowerRankTime = math.floor(app.session:getServerTime() or os.time())
        local datas = {}
        for k,v in pairs( msg.guildMembers ) do
            local userBaseInfo = rawget(v, "userBaseInfo")
            if userBaseInfo then
                local roleId = rawget(userBaseInfo, "uid") or 0 
                local power = rawget(userBaseInfo, "combatPower") or 0
                table.insert(datas, {roleId = roleId, power = power})
            end
        end
        table.sort(datas, function(a, b)
            return a.power > b.power
        end)
        local myRoleId = UD.player.uid
        for k, v in pairs(datas) do
            if myRoleId == v.roleId then
                self._myInGuildPowerRank = k
                self._myGuildMemberNum = #datas
                EM:notify(ViewEvent.CSGuildWar_MyPowerRankInGuild, k, #datas)
                break
            end
        end
	end)
end






-- function CSGuildWarData:testMatchInfo()
--     local testData = {
--         guild1 = {
--             info = {
--                 flagAdditionalIcon = "Gicon_d_09",
--                 flagAdditionalIconColor = 8,
--                 flagBaseIcon = "Gicon_d_09",
--                 flagBaseIconColor = 8,
--                 highestCombatPowr = 187185,
--                 leaderID = 1884716,
--                 leaderName = "萱炫",
--                 lv = 5,
--                 memberNum = 84,
--                 name = "测试1",
--                 server = 20039,
--                 totalCombatPower = 6878334,
--                 totalContribution = 98600,
--                 uuid = "Vvsf41z4HLLLHKXj",
--                 flagAdditionalIcon = "Gicon_d_09",
--             },
--             rank = 104,
--         },
--         guild2 = {
--             info = {
--                 flagAdditionalIcon = "Gicon_d_09",
--                 flagAdditionalIconColor = 8,
--                 flagBaseIcon = "Gicon_d_09",
--                 flagBaseIconColor = 8,
--                 highestCombatPowr = 187185,
--                 leaderID = 1884716,
--                 leaderName = "萱炫",
--                 lv = 5,
--                 memberNum = 84,
--                 name = "测试2",
--                 server = 20039,
--                 totalCombatPower = 6878334,
--                 totalContribution = 98600,
--                 uuid = "gGsUQ1fYLLLL8ezQ",
--                 flagAdditionalIcon = "Gicon_d_09",
--             },
--             rank = 52,
--             winTimes = 1,
--         },
--         id     = 156,
--         round = 3,
--         -- winner = "Vvsf41z4HLLLHKXj",
--     }
--     return testData
-- end



return CSGuildWarData